package com.example.myblog.controller;

import com.example.myblog.pojo.Comment;
import com.example.myblog.pojo.User;
import com.example.myblog.service.CommentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Date;


/**
 * @BelongsProject: MyBlog
 * @BelongsPackage: com.example.myblog.controller
 * @ClassName CommentController
 * @CreateTime: 2025-06-10  10:06
 * @Author: TangLiFei
 */
@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;

    // 显示文章评论
    @GetMapping("/comments")
    public String showComments(@RequestParam("articleId") Integer articleId,
                               @RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "10") int count,
                               Model model) {
        PageInfo<Comment> commentPageInfo = commentService.getComments(articleId, page, count);
        model.addAttribute("comments", commentPageInfo.getList());
        model.addAttribute("articleId", articleId);
        return "commentBackend"; // 返回显示评论的页面
    }

    @PostMapping("/addComment")
    public String addComment(Comment comment, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            comment.setAuthor(user.getAccount());
        }
        try {
            comment.setCreated(new Date());
            commentService.pushComment(comment);
            return "redirect:/articleDetail?id=" + comment.getArticleId();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }


    // 删除评论
    @GetMapping("/deleteComment")
    public String deleteComment(@RequestParam("id") Integer id) {
        commentService.deleteCommentById(id);
        return "forward:/Commentbackend";
    }
}
